package com.pt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.entity.Request;
import com.pt.entity.User;
import com.pt.entity.Torrent;
import com.pt.dto.response.RequestResponse;
import com.pt.mapper.RequestMapper;
import com.pt.service.RequestService;
import com.pt.service.UserService;
import com.pt.service.NotificationService;
import com.pt.service.TorrentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RequestServiceImpl implements RequestService {
    
    private final RequestMapper requestMapper;
    private final UserService userService;
    private final NotificationService notificationService;
    private final TorrentService torrentService;
    
    @Override
    public IPage<RequestResponse> getRequests(Page<RequestResponse> page, Integer categoryId, Integer status) {
        // 创建查询用的Page对象
        Page<Map<String, Object>> mapPage = new Page<>(page.getCurrent(), page.getSize());
        
        // 查询包含关联信息的数据
        IPage<Map<String, Object>> mapResult = requestMapper.selectRequestsWithInfo(mapPage, categoryId, status);
        
        // 转换为RequestResponse对象
        IPage<RequestResponse> result = new Page<>(page.getCurrent(), page.getSize());
        result.setTotal(mapResult.getTotal());
        result.setPages(mapResult.getPages());
        result.setRecords(
            mapResult.getRecords().stream()
                .map(RequestResponse::fromMap)
                .collect(Collectors.toList())
        );
        
        return result;
    }
    
    @Override
    public RequestResponse getRequestById(Long requestId) {
        Map<String, Object> map = requestMapper.selectRequestWithInfoById(requestId);
        return map != null ? RequestResponse.fromMap(map) : null;
    }
    
    @Override
    @Transactional
    public Request createRequest(Request request) {
        // 扣除用户魔力值
        User user = userService.getUserById(request.getRequesterId());
        user.setBonusPoints(user.getBonusPoints() - request.getRewardPoints());
        userService.updateUser(user);
        
        requestMapper.insert(request);
        return request;
    }
    
    @Override
    @Transactional
    public void fillRequest(Long requestId, Long torrentId, Long fillerId) {
        System.out.println("=== fillRequest调用 ===");
        System.out.println("requestId: " + requestId);
        System.out.println("torrentId: " + torrentId);
        System.out.println("fillerId: " + fillerId);
        
        Request request = requestMapper.selectById(requestId);
        System.out.println("找到的request: " + request);
        
        if (request != null && request.getStatus() == 0) { // 只有进行中的求种才能完成
            System.out.println("开始完成求种，当前状态: " + request.getStatus());
            request.setStatus(1); // 已完成
            request.setFillerId(fillerId);
            request.setFilledTorrentId(torrentId);
            request.setFilledTime(LocalDateTime.now());
            
            int updateResult = requestMapper.updateById(request);
            System.out.println("更新求种结果: " + updateResult);
            
            // 给完成者奖励魔力值
            User filler = userService.getUserById(fillerId);
            System.out.println("完成者: " + filler.getUsername() + ", 当前魔力值: " + filler.getBonusPoints());
            filler.setBonusPoints(filler.getBonusPoints() + request.getRewardPoints());
            userService.updateUser(filler);
            System.out.println("完成者奖励后魔力值: " + filler.getBonusPoints());
            
            // 发送通知
            try {
                Torrent torrent = torrentService.getById(torrentId);
                String torrentTitle = torrent != null ? torrent.getTitle() : "未知种子";
                
                // 通知求种者
                User requester = userService.getUserById(request.getRequesterId());
                notificationService.sendSystemNotification(
                    request.getRequesterId(), 
                    "求种完成", 
                    String.format("您的求种请求【%s】已被用户【%s】完成", request.getTitle(), filler.getUsername())
                );
                
                // 通知完成者
                notificationService.sendSystemNotification(
                    fillerId, 
                    "完成求种奖励", 
                    String.format("您完成了求种【%s】，获得%d魔力值奖励", request.getTitle(), request.getRewardPoints())
                );
                
                System.out.println("求种完成通知发送成功");
            } catch (Exception e) {
                System.out.println("发送求种完成通知失败: " + e.getMessage());
            }
        } else {
            System.out.println("无法完成求种: request为null或状态不正确");
            if (request != null) {
                System.out.println("当前状态: " + request.getStatus());
            }
        }
    }
    
    @Override
    @Transactional
    public void closeRequest(Long requestId, Long userId) {
        Request request = requestMapper.selectById(requestId);
        if (request != null && request.getRequesterId().equals(userId) && request.getStatus() == 0) { // 只有进行中的求种才能关闭
            request.setStatus(2); // 已关闭
            requestMapper.updateById(request);
            
            // 退还魔力值给发起者
            User requester = userService.getUserById(userId);
            requester.setBonusPoints(requester.getBonusPoints() + request.getRewardPoints());
            userService.updateUser(requester);
        }
    }
} 